<?php


namespace app\home\controller\articles;



use app\home\controller\Base;


use app\home\model\Essay;
use app\home\model\Classify;
use app\home\service\CodeService;
use app\home\service\TokenService;
use think\Db;
class Index  extends Base
{

    protected $model;
    protected $classify;
    protected $uid;

    /**
     * @param {name}
     * @var mixed
     */
    protected $param;
    protected $offset;
    protected $limit = 10;


    public function __construct(Classify $classify,Essay $model)
    {
        $this->model = $model;
        $this->classify = $classify;
        $this->uid = TokenService::getUserInfoFromToken('u_id');
        $this->param = input('post.');
    }


    /**
     * 获取分类
     * @return array
     */
    public function getClassify(){

        if(is_array($this->uid))  return $this->uid;
        $res = $this->classify->select();
        foreach ($res as $key=>$val){
            $res[$key]['type'] = $val['id'];
            unset($val['id']);
        }
        return !empty($res) ? CodeService::response(200,'获取成功',$res):CodeService::response(201,'暂无数据');
    }

    /**
     * 获取文章列表
     * @param int  page
     * @param int type
     * @return array
     */
    public function getArticleList(){

        if(is_array($this->uid))  return $this->uid;
        if(empty($this->param['page']) ) return  CodeService::MISSING_PARAMETERS;
        $map =[];
        if(isset($this->param['type'])){
            if(empty($this->param['type']) ) return  CodeService::MISSING_PARAMETERS;
            $map = ['type_id'=>$this->param['type']];
        }
        $this->offset  = $this->param['page']-1;
        $this->limit = isset($this->param['limit']) ? $this->param['limit'] : $this->limit;
        $res = $this->model->where($map)->limit($this->offset * $this->limit, $this->limit)->field(['delete_time','update_time','create_time','content'],true)->select();
//        foreach ($res as $key=>$val){
//            $res[$key]['img'] = config('h5'). '/public/common/icon/user.png';
//        }
        return !$res->isEmpty() ? CodeService::response(200,'获取成功',$res):CodeService::response(201,'暂无数据');
    }


    /**
     * 获取文章向详情
     * @param int  id
     * @return array
     */
    public function getArticleDetail(){
        if(is_array($this->uid))  return $this->uid;
        if( empty($this->param['id'])) return  CodeService::MISSING_PARAMETERS;
        Db::startTrans();
        try {
            $res = $res = $this->model->where('id',$this->param['id'])->field(['delete_time','update_time'],true)->find();
            $this->model->where('id',$this->param['id'])->setInc('ready_num');
            // 提交事务
            Db::commit();
            return !empty($res) ?  CodeService::response(200,'获取成功',$res):CodeService::response(201,'暂无数据');
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return CodeService::SERVER_ERROR_TRY_AGAIN_LATER;

        }
    }



}